package com.nuanshui.heatedloan.service.services;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.security.MD5Util;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.model.Pair;
import com.nuanshui.framework.utils.model.StringObjPair;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.model.SafeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by wangxw on 2017/6/27.
 */

@Component
public class SafeTokenUtil {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserTokenService userTokenService;

    @Autowired
    private JedisUtil jedisUtil;

    public Pair<String,String> generateToken(String version) {
        LogUtil.info(logger, "根据app版本:" + version + "safeToken");
        String randomNum = SysStringUtils.getRandomString(6);
        String str = new Date().getTime() + "";
        str = randomNum + str.substring(6);

        //二次加密
        String md5Str = MD5Util.md5(str + version).toLowerCase();
        String md5StrNew= MD5Util.md5(md5Str+version).toLowerCase();
        SafeToken safeToken = new SafeToken();
        UserAgent userAgent = (UserAgent) getServletRequest().getAttribute(GlobalParam.USER_AGENT);
        if(userAgent!=null)
        {
            safeToken.setClient(userAgent.getClient());
            safeToken.setVersion(userAgent.getVersion());
        }
        //以前放的是md5Str   现在放的是userAgent.getSafeToken()
        safeToken.setSafeToken(md5StrNew);
        logger.info(md5StrNew);
        userTokenService.saveSafeToken(safeToken);
        return new Pair<String,String>(md5Str,md5StrNew);
    }

    HttpServletRequest getServletRequest() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest();
    }

}
